from appserver import db_store
import traceback

# from models.entity.button import Button


class RoleWithButton(db_store.Model):
	__tablename__="roles_with_buttons"
	__bind_key__="main"

	# id=db_store.Column(db_store.Integer,primary_key=True)
	role_id=db_store.Column(db_store.Integer,db_store.ForeignKey("roles.id"),nullable=False,primary_key=True)
	button_id=db_store.Column(db_store.Integer,db_store.ForeignKey("buttons.id"),nullable=False,primary_key=True)

	def __repr__(self):
		return "<RoleWithButton %d+%d>" %(self.role_id,self.button_id)

	def save(self):
		if self.role_id is None:
			print("RoleWithButton save error: role_id cannot be empty")
			return -1
		if self.button_id is None:
			print("RoleWithButton save error: button_id cannot be empty")
			return -2
		try:
			db_store.session.add(self)
			db_store.session.commit()
			return 0
		except:
			print("table roles_with_buttons write error:\n--------------------\n%s\n----------------------" %(traceback.format_exc()))
			db_store.session.rollback()
			return -3

	def delete(self):
		# id=self.id
		try:
			db_store.session.delete(self)
			db_store.session.commit()
			return 0
		except:
			print("RoleWithButton(id=%d) delete  error:\n-------------------\n%s\n----------------------" (id,traceback.format_exc()))
			db_store.session.rollback()
			return -1

	@staticmethod
	def get_role_with_button_by_button_id(id_num):
		return RoleWithButton.query.filter_by(button_id=id_num).first()

	#####我加的方法8-28 Button引不进来,所以写到了button实例中
	# @staticmethod
	# def get_role_with_buttons_by_role_id(id_num):
	# 	connectors = RoleWithButton.query.filter_by(role_id=id_num).all()
	# 	# print('connectors', connectors)
	# 	rlist = []
	# 	for item in connectors:
	# 		# print('item', item)
	# 		rlist.append(Button.query.filter_by(id=item.button_id).first())
	# 	print('rlist', rlist)
	# 	return rlist

	@staticmethod
	def add_buttons_to_role(role,buttons):
	    # 向指定用户添加一组按钮
	    # 用法:
	    #       role 角色实例
	    #       buttons 按钮实例的列表
	    for item in buttons:
	        button_connector=RoleWithButton()
	        button_connector.role_id=role.id
	        button_connector.button_id=item.id
	        if button_connector.save()!=0:
	            return -1
	    return 0
	####我的方法8-28
	@staticmethod
	def add_buttons_to_role_id(role_id, buttons):
		# 向指定用户添加一组按钮
		# 用法:
		#       role_id 角色id
		#       buttons 按钮id的列表
		for item in buttons:
			button_connector = RoleWithButton()
			button_connector.role_id = role_id
			button_connector.button_id = item
			if button_connector.save() != 0:
				return -1
		return 0
